﻿using AutoMapper;
using Finance.Api.Write.Applications.Commands.财务管理.Receives;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;
using System.Security.Claims;

namespace Finance.Api.Write.Applications.CommandHands.财务管理.ReturnMonerys.Receives
{
    public class ReceiveUpdataCommandHandler : IRequestHandler<ReceiveUpdataCommand, ApiResult<bool>>
    {
        private readonly SqlsugarDb<Receive> db;
        private readonly IMapper mapper;
        private readonly IHttpContextAccessor httpContextAccessor;
        public ReceiveUpdataCommandHandler(SqlsugarDb<Receive> db, IMapper mapper, IHttpContextAccessor httpContextAccessor)
        {
            this.db = db;
            this.mapper = mapper;
            this.httpContextAccessor = httpContextAccessor;
        }
        public async Task<ApiResult<bool>> Handle(ReceiveUpdataCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<bool>();
            try
            {
                if (request.IsInvoice == 1 || request.IsInvoice == 2)
                {
                    var entity = await db.FirstQuery().FirstAsync(x => x.Id == request.Id);
                    if (entity == null)
                    {
                        result.message = "查无数据";
                        result.Code = Enumcode.fail;
                    }
                    entity = mapper.Map(request, entity);
                    entity.UpdateTime = DateTime.Now;
                    entity.UpdateName = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name)?.Value;
                    entity.LoginId = Convert.ToInt32(httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value);

                    var updataResult = await db.Updata(entity);
                    if (updataResult > 0)
                    {
                        result.message = "收款信息修改成功";
                        result.data = true;
                        result.Code = Enumcode.ok;
                    }
                    else
                    {
                        result.message = "收款信息修改失败";
                        result.data = false;
                        result.Code = Enumcode.fail;
                    }

                }
                else
                {
                    result.message = "输入数据不合法";
                    result.Code = Enumcode.Errordata;
                    result.data = false;
                    return result;
                }
            }
            catch (Exception ex)
            {
                result.message =ex.Message;
                result.data = false;
                result.Code = Enumcode.fail;
            }
            return await Task.FromResult(result);
        }
    }
}
